/* 
    加载模块
*/

let path = require("path"); //路径处理模块
let express = require("express"); //加载框架
let app = express(); //调用框架顶级方法得到一个对象
let hbs = require("hbs"); //加载模板模块,才可以在html中使用node发送过去的对象（数据）,需要手动下载 npm i hbs
let sql = require("./model/sql");
let formidable = require("formidable");
let fs = require("fs");
let multer = require("multer");
let querystring = require("querystring"); //数据处理模块
app.set("views", path.join(__dirname, "views"));
app.use(express.static(path.join(__dirname, "public")));
app.engine("html", hbs.__express);
let session = require("express-session"); //引入session模块
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//设定port变量，作为访问端口
app.set("port", process.env.PORT || 8686);

// 设置views变量，html页面存放目录
app.set("views", path.join(__dirname, "views"));

// 设置静态资源目录
app.use(express.static(path.join(__dirname, "public")));

// 设定使用模板后缀名
app.set("view engine", "html"); //模板后缀名可以根据自己的需求做修改

//运行模板方法
app.engine("html", hbs.__express);

// 中间件
app.use(
    session({
        secret: "xzsagjasoigjasoi",
        resave: true, //强制保存session
        cookie: {
            maxAge: 7 * 24 * 60 * 60 * 1000, //设置session的有效期为1周
        },
        saveUninitialized: true, //是否保存初始化的session
    })
);

// 当前登陆用户的信息
let userMsg = null;

// 路由处理静态页面
app.get("/", function(req, res) {
    // 重定向
    res.redirect("/index");
});

// 加载登录页
app.get("/login", function(req, res, next) {
    res.render("login");
});
// 加载注册页
app.get("/registered", function(req, res, next) {
    res.render("registered");
});
// 渲染头部
app.get("/header", function(req, res) {
    // console.log(req.session);
    if (req.session.userMsg) {
        //判断session 状态

        res.render("header", {
            userMsg: req.session.userMsg,
        });
    } else {
        res.render("header");
    }
});

// 获取传过来的账号密码
app.post("/login", function(req, res) {
    let obj = req.body;
    sql.loginCheck(obj, function(data) {
        if (data.length == 0) {
            res.send("error!");
        } else {
            userMsg = JSON.parse(JSON.stringify(data[0]));
            req.session.userMsg = JSON.parse(JSON.stringify(data[0]));
            // let userMsg = JSON.parse(JSON.stringify(req.session.userMsg[0]));
            res.redirect("/index");
            // res.render("/index", userMsg);
        }
    });
});

// 注册
app.post("/registered", function(req, res) {
    let obj = req.body;
    sql.email(obj, function(data) {
        if (data.length > 0) {
            res.render("registered", { state: `0` });
        } else {
            sql.registered(obj);
            res.render("index", { state: `1` });
        }
    });
});

// 加载首页
app.get("/index", function(req, res) {
    if (req.session.userMsg) {
        res.render("index", {
            userMsg: req.session.userMsg,
        });
    } else {
        res.render("index");
    }
    // console.log(req.session);
});

// 退出登录
app.get("/loginout", function(req, res) {
    req.session.userMsg = null; // 删除session
    res.render("index");
});

// // 加载详情页
app.get("/details/:articleid", function(req, res) {
    // let id = req.params.articleid;
    // console.log(id)
    res.render("details");
});

// 加载发布话题页面
app.get("/editTopic", (req, res) => {
    res.render("edit");
});

// 上传图片
app.post("/uploadImg", (req, res) => {
    // let userid = req.session.userMsg[0].uid;
    // let { tab, title, content } = req.body;
    let form = new formidable.IncomingForm();
    let dir = "./public/uploadImg/";
    form.uploadDir = dir;
    form.parse(req, function(err, fields, files) {
        // console.log(files['editormd-image-file'].path)
        // console.log(files.name)
        let oldPath = files["editormd-image-file"].path; //fileName就是我们刚在前台模板里面配置的后台接受的名称；
        let extname = files["editormd-image-file"].name; //获取图片名称
        // //新的路径由组成：原父路径 + 拓展名
        let newPath = dir + extname;
        //改名     把之前存的图片换成真的图片的完整路径
        fs.rename(oldPath, newPath, function(err) {
            if (err) {
                console.log(err);
                res.send({ isOk: false, err });
            }
            let resPath = newPath.replace("./public", "http://localhost:8686"); //处理图片路径  让前端能访问
            // console.log(resPath);
            res.json({ success: 1, message: "上传成功", url: resPath });
            // res.send({ isOk: true }) //返回图片路径
        });
    });
});

// 发布文章
app.post("/publishTopic", (req, res) => {
    let { tab, title, content } = req.body;
    let userid = req.session.userMsg.uid;
    let sqls = `insert into topics (author_id,tab,title,content) values ('${userid}','${tab}','${title}','${content}')`;
    sql.publish(sqls, function(data) {
        if (data) {
            res.send(true);
        }
    });
});

// 个人设置页面
app.get("/setting", (req, res) => {
    var id = req.session.userMsg.uid;
    sql.getUserMsg(id, function(data) {
        res.render("setting", {
            datas: data,
        });
    });
});

app.post(
    "/setting",
    multer({
        //设置文件存储路径
        dest: "./public/avatar", //upload文件如果不存在则会自己创建一个。
    }).single("file"),

    function(req, res) {
        let { user_name, email, sign } = req.body;
        var id = req.session.userMsg.uid;
        if (!req.file) {
            // console.log(JSON.parse(JSON.stringify(req.session.userMsg))[0]);
            let sqlstr = `update users set user_name='${user_name}',email='${email}',sign='${sign}' where uid=${id}`;
            sql.updateMsg(sqlstr, function(data) {
                sql.getUserMsg(id, function(data) {
                    userMsg = data;
                    res.render("setting", {
                        datas: data,
                        success: true,
                    });
                });
            });
        } else {
            let file = req.file;
            // let fileInfo = {};
            fs.renameSync(
                "./public/avatar/" + file.filename,
                "./public/avatar/" + file.originalname
            );

            let sqlstr = `update users set user_name='${user_name}',email='${email}',avatar_url='${file.originalname}',sign='${sign}' where uid=${id}`;
            sql.updateMsg(sqlstr, function(data) {
                sql.getUserMsg(id, function(data) {
                    userMsg = data;
                    res.render("setting", {
                        datas: data,
                        success: true,
                    });
                });
            });
        }
    }
);

// 修改密码
app.post("/updatePass", function(req, res) {
    let { oldpass, newpass } = req.body;
    console.log(oldpass, newpass);
    if (oldpass == userMsg.user_pass) {
        let sqlstr = `update users set user_pass='${newpass}' where uid=${userMsg.uid}`;
        sql.updateMsg(sqlstr, function(data) {
            sql.getUserMsg(userMsg.uid, function(data) {
                userMsg = data;
            });
            res.send(true);
        });
    } else {
        res.send(false);
    }
});

// 查看话题页面
app.get("/topic", function(req, res) {
    res.render("topic");
});

// 监听窗口
app.listen(app.get("port"), function() {
    console.log("   连接成功:" + app.get("port"));
});